﻿//-----------------------------------------------------------------------
// <copyright file="D3DDeviceManager.cs" company="Flaxen Geo">
//    Copyright (c) 2011, Michael P. Gerlek.  All rights reserved.
// </copyright>
//
// Redistribution and use in source and binary forms, with or without 
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, 
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Flaxen Geo nor the names of its contributors may be 
//   used to endorse or promote products derived from this software without 
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
// THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------

namespace Flaxen.SlimDXControlLib
{
    using System;
    using System.Runtime.InteropServices;
    using SlimDX.Direct3D9;

    /// <summary>
    /// This class owns the DirectX device and the shared texture.  The class holds 
    /// singleton data (BUG: it is not threadsafe yet, to lock down the singleton).
    /// </summary>
    internal static class D3DDeviceManager
    {
        private static int s_numActiveImages = 0;
        private static Direct3DEx s_d3dContext;
        private static DeviceEx s_d3dDevice;

        /// <summary>
        /// Gets the texture to be rendered on to.
        /// </summary>
        public static Texture SharedTexture { get; private set; }

        /// <summary>
        /// Initializes the D3D world, as needed.
        /// </summary>
        public static void Create()
        {
            if (s_numActiveImages > 0)
            {
                return;
            }

            InitD3D9();
            ++s_numActiveImages;

            return;
        }

        /// <summary>
        /// Shutdown the D3D world.
        /// </summary>
        public static void Destroy()
        {
            s_numActiveImages--;

            ClearSharedTexture();

            ShutdownD3D9();
        }

        /// <summary>
        /// Given a texture, make a shared texture for the D3DImage to use.
        /// </summary>
        /// <param name="texture">The texture to be used for the shared texture</param>
        public static void CreateSharedTexture(SlimDX.Direct3D10.Texture2D texture)
        {
            Format format = TranslateFormat(texture);
            if (format == Format.Unknown)
            {
                throw new ArgumentException("Texture format is not compatible with OpenSharedResource");
            }

            IntPtr handle = GetSharedHandle(texture);
            if (handle == IntPtr.Zero)
            {
                throw new ArgumentException("Texture handle is null");
            }

            SharedTexture = new Texture(s_d3dDevice, texture.Description.Width, texture.Description.Height, 1, Usage.RenderTarget, format, Pool.Default, ref handle);
        }

        /// <summary>
        /// Dispose of the shared texture.
        /// </summary>
        public static void ClearSharedTexture()
        {
            if (SharedTexture != null)
            {
                SharedTexture.Dispose();
                SharedTexture = null;
            }
        }

        private static IntPtr GetSharedHandle(SlimDX.Direct3D10.Texture2D texture)
        {
            SlimDX.DXGI.Resource resource = new SlimDX.DXGI.Resource(texture);
            IntPtr result = resource.SharedHandle;

            resource.Dispose();

            return result;
        }

        private static Format TranslateFormat(SlimDX.Direct3D10.Texture2D texture)
        {
            switch (texture.Description.Format)
            {
                case SlimDX.DXGI.Format.R10G10B10A2_UNorm:
                    return SlimDX.Direct3D9.Format.A2B10G10R10;

                case SlimDX.DXGI.Format.R16G16B16A16_Float:
                    return SlimDX.Direct3D9.Format.A16B16G16R16F;

                case SlimDX.DXGI.Format.B8G8R8A8_UNorm:
                    return SlimDX.Direct3D9.Format.A8R8G8B8;

                default:
                    return SlimDX.Direct3D9.Format.Unknown;
            }
        }

        private static void InitD3D9()
        {
            s_d3dContext = new Direct3DEx();

            PresentParameters presentparams = new PresentParameters();
            presentparams.Windowed = true;
            presentparams.SwapEffect = SwapEffect.Discard;
            presentparams.DeviceWindowHandle = SafeNativeMethods.GetDesktopWindow();
            presentparams.PresentationInterval = PresentInterval.Immediate;

            s_d3dDevice = new DeviceEx(s_d3dContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams);
        }

        private static void ShutdownD3D9()
        {
            if (s_d3dDevice != null)
            {
                s_d3dDevice.Dispose();
                s_d3dDevice = null;
            }

            if (s_d3dContext != null)
            {
                s_d3dContext.Dispose();
                s_d3dContext = null;
            }
        }

        /// <summary>
        /// Class to hold some dll imports.
        /// </summary>
        internal static class SafeNativeMethods
        {
            #region DllImports
            [DllImport("user32.dll", SetLastError = false)]
            public static extern IntPtr GetDesktopWindow();
            #endregion
        }
    }
}
